import 'package:flutter/widgets.dart';
import 'package:intl/intl.dart';

const List<String> units = [
  '',
  '万',
  '亿',
  '兆',
  '京',
  '垓',
  '秭',
  '穰',
  '沟',
  '涧',
  '正',
  '载'
];
const List<String> linkUnits = ['', '拾', '佰', '仟'];
const List<String> digits = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'];
const List<String> decimalUnits = ['角', '分'];

extension Helper on String {
  /// 为了解决系统排版时，中文 和 英文 交界处 换行的问题。向文本中加入一个 Zero-width space (\u{200B})
  String get joinZeroWidthSpace => Characters(this).join('\u{200B}');

  String get upperCase {
    if (this.isEmpty) {
      return "";
    }
    final splitResult = this.split(".");
    String integerPart = splitResult.first;
    String? decimalPart = splitResult.length >= 2 ? splitResult.last : null;
    String result = '';
    int unitIndex = 0;
    while (integerPart.isNotEmpty) {
      String subPart = integerPart.length > 4
          ? integerPart.substring(integerPart.length - 4)
          : integerPart;
      integerPart = integerPart.length > 4
          ? integerPart.substring(0, integerPart.length - 4)
          : '';
      String subResult = '';
      bool hasZero = false;
      for (int i = 0; i < subPart.length; i++) {
        int digit = int.parse(subPart[i]);
        if (digit == 0) {
          hasZero = true;
        } else {
          if (hasZero) {
            subResult += digits[0];
            hasZero = false;
          }
          subResult += digits[digit] + linkUnits[subPart.length - 1 - i];
        }
      }

      if (subResult.isNotEmpty) {
        subResult += units[unitIndex];
        result = subResult + result;
      }
      unitIndex++;
    }

    if (result.isEmpty) {
      result = digits[0];
    }

    if (decimalPart != null && decimalPart.isNotEmpty) {
      final decimalPartDigit = int.tryParse(decimalPart) ?? 0;
      if (decimalPartDigit > 0) {
        result += "元";
        for (int i = 0; i < decimalPart.length; i++) {
          int digit = int.tryParse(decimalPart[i]) ?? 0;
          if (digit != 0) {
            result += digits[digit] + decimalUnits[i];
          }
        }
      } else {
        result += "元整";
      }
    } else {
      result += "元整";
    }

    return result;
  }

  String? formatDate({String format = "yyyy-MM-dd"}) {
    final date = DateTime.tryParse(this);
    if (date != null) {
      return DateFormat(format).format(date);
    }
    return null;
  }
}
